package clients

import (
	"DCOS-API/SDK/client-go/kubernetes"
	"DCOS-API/SDK/client-go/tools/clientcmd"
	clientcmdapi "DCOS-API/SDK/client-go/tools/clientcmd/api"
	"DCOS-API/dbs"
	"DCOS-API/model"
	"encoding/json"
	"fmt"
)

var clientSet map[string]*kubernetes.Clientset

func GetK8sCli(label string) *kubernetes.Clientset {
	if label == "" {
		return nil
	}
	if clientSet == nil {
		clientSet = make(map[string]*kubernetes.Clientset)
		db := dbs.Mysql()
		clusters := make([]*model.Cluster, 0)
		db.Model(new(model.Cluster)).Scan(&clusters)
		for _, v := range clusters {
			cnf, err := clientcmd.BuildConfigFromKubeconfigGetter(v.MasterUrl, func() (*clientcmdapi.Config, error) {
				c := new(clientcmdapi.Config)
				err := json.Unmarshal([]byte(v.Config), c)
				if err != nil {
					return nil, err
				}
				return c, nil
			})
			if err != nil {
				panic(fmt.Sprintf("解析k8s配置文件失败：%+v\n", err.Error()))
			}
			cli, err := kubernetes.NewForConfig(cnf)
			if err != nil {
				panic(fmt.Sprintf("获取k8sCli失败：%+v\n", err.Error()))
			}
			clientSet[v.ClusterLabel] = cli
		}
	}
	cli, ok := clientSet[label]
	if !ok {
		return nil
	}
	return cli
}
